const Base = require('./base.js');

module.exports = class extends Base {
    indexAction() {
        return this.display();
    }
    async loginAction() {
        const self = this;
        const param = this.post();
        think.logger.info(self.ctx.request);
        const data = await this.model('sys_user').login(param);
        if (think.isEmpty(data)) {
            return this.fail(9996, '用户名或密码错误');
        } else {
            console.log(data);
            data.token = await this.service('token').createToken(data);
            data.menu = await this.model('sys_menu').getMyMenuData(data.id, data.role_id);
            return this.success(data);
        }
    }

    async AddUserAction(){
        const params = this.post();
        params.role_id = 2;
        params.status = 1;
        params.role_name = '普通用户';
        params.password = think.md5(params.username);
        let affRows = await this.model("sys_user").add(params);
        if(affRows != 0){
            return this.success("添加成功");
        }
    }

    async EditUserAction(){
        let params = this.post()
        let affRows = await this.model("sys_user").update(params);
        if(affRows != 0){
            return this.success("更新成功");
        }else{
            return this.fail("更新失败")
        }
    }
    
    async GetUserListAction(){
        const params = this.post();
        const data = await this.model("sys_user").select();
        return this.success(data);
    }

    async GetUserByConditionAction(){
        let params = this.post();
        let where = "";
        if(params['name'] != ""){
            where += `AND name LIKE '%${params['name']}%'`;
        }
        if(params['username'] != ""){
            where += `AND username LIKE '%${params['username']}%'`;
        }

        let sql = `SELECT * FROM sys_user WHERE status = 1 AND role_id = 2 ${where}`;
        let sqlOptions = this.model().parseSql(sql);
        let data = await this.model().query(sqlOptions);
        
        let res = {
            count:data.length,
            data:data.slice((params.page-1) * params.pageSize, (params.page * params.pageSize))
        }
        //console.log(res);
        return this.success(res);
    }

    async DeleteUserAction(){
        let params = this.post();
        let data = await this.model("sys_user").where({id: params.id}).update({status:0});
        if(data != 0){
            return this.success("删除成功");
        }
    }
    async pageDataAction() {
        const param = this.post();
        const data = await this.model('sys_user').pageData(param);
        return this.success(data);
    };
};